<!DOCTYPE>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>动态饼图</title>
    <style type="text/css">
        body{
            margin: 0;
            overflow: hidden;
            background: #fff;
            font: 12px sans-serif;
        }
        #map{
            position: relative;
            height: 553px;
            border:1px solid #3473b7;
        }
        .arc path {
            stroke: #fff;
        }
    </style>
    <link href='./css/bootstrap.min.css' rel='stylesheet' />
    <link href='./css/bootstrap-responsive.min.css' rel='stylesheet' />
    <script src='../libs/SuperMap.Include.js'></script>
    <script src="js/d3.v3.min.js"></script>
    <script type="text/javascript">
        var map, infowin, layer, utfgrid, control, d3Layer,
                host = document.location.toString().match(/file:\/\//)?"http://localhost:8090":'http://' + document.location.host,
                url=host+"/iserver/services/map-china400/rest/maps/China";
        var pieChartDom;
        var elementsDiv;
        var isMapMoving = false;
        //判断浏览器是否支持 Svg
        function hasSVG(){
            var doc = document;
            var SVG_NS = 'http://www.w3.org/2000/svg';
            return !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect;
        }

        function init(){
            if(!hasSVG()){
                alert('您的浏览器不支持 SVG，请升级！');
                return;
            }

            //ie 9 支持 svg，但不完善，不能正常运行此范例
            if(SuperMap.Browser.name === "msie" && SuperMap.Browser.version.indexOf("9") !== -1)
            {
                alert('您的浏览器不支持本范例，请升级！');
                return;
            }

            map = new SuperMap.Map("map", {controls: [
                new SuperMap.Control.ScaleLine(),
                new SuperMap.Control.Zoom(),
                new SuperMap.Control.LayerSwitcher(),
                new SuperMap.Control.Navigation({
                    dragPanOptions: {
                        enableKinetic: true
                    }
                })],
                projection: "EPSG:3857"
            });

            //地图移动过程中不显示图表
            map.events.on({"movestart": function(){
                document.getElementById("piechart").innerHTML = "";
                isMapMoving = true;
            }});
            map.events.on({"moveend": function(){
                isMapMoving = false;
            }});

            //基础图层
            layer = new SuperMap.Layer.TiledDynamicRESTLayer("China", url, {transparent: true}, {useCanvas: true, maxResolution: "auto"});

            //创建 Elements 图层，用于显示饼图
            d3Layer = new SuperMap.Layer.Elements("D3Layer");

            //获取 Elements 图层 div
            elementsDiv =  d3Layer.getDiv();
            //设置Elements实例的div为地图大小
            var mapsize = map.getSize();
            elementsDiv.style.width = mapsize.w;
            elementsDiv.style.height = mapsize.h;

            //创建图表 div, 设置其基本属性, 并添加到  Elements 图层
            pieChartDom = document.createElement("div");
            pieChartDom.id = "piechart";
            pieChartDom.style.width = 128;
            pieChartDom.style.height = 128;
            pieChartDom.style.position = "absolute";
            pieChartDom.style.opacity = 0.8;
            elementsDiv.appendChild(pieChartDom);

            //创建 UTFGrid 图层，用于更新饼图数据
            utfgrid = new SuperMap.Layer.UTFGrid("UTFGridLayer", url,
                    {
                        layerName: "China_Province_pl@China",
                        utfTileSize: 256,
                        pixcell: 8,
                        isUseCache: true
                    },
                    {
                        utfgridResolution: 8
                    });

            layer.events.on({"layerInitialized": addLayer});
            control = new SuperMap.Control.UTFGrid({
                layers: [utfgrid],
                callback: callback,
                handlerMode: "move"
            });
            map.addControl(control);
        }

        var callback = function (infoLookup, loc, pixel) {
            if (infoLookup && isMapMoving === false) {
                var info;
                for (var idx in infoLookup) {
                    info = infoLookup[idx];
                    if (info && info.data) {
                        document.getElementById("piechart").innerHTML = "";

                        //全国面积取 9.6e12（960万平方千米）
                        var anotherArea = 9.6e12 - info.data.SmArea;

                        // 计算面积比
                        var theArea = ((info.data.SmArea/9.6e12)*100).toFixed(2);
                        var allArea = ((anotherArea/9.6e12)*100).toFixed(2);

                        //组织 D3 PieDChart 数据
                        var data = [
                            {
                                "NAME": "其他省份" + allArea + "%",
                                "SmArea":  anotherArea
                            },
                            {
                                "NAME": info.data.NAME + theArea + "%",
                                "SmArea": info.data.SmArea
                            }
                        ]

                        //取图表 div 大小作为创建图表的参数
                        var width = parseFloat(pieChartDom.style.width),
                                height = parseFloat(pieChartDom.style.height),
                                radius = Math.min(width, height) / 2;

                        //图表位置
                        pieChartDom.style.left = pixel.x - width/2;
                        pieChartDom.style.top = pixel.y - height/2;

                        var color = d3.scale.ordinal()
                                .range(["#1874CD", "#87CEFA"]);

                        var arc = d3.svg.arc()
                                .outerRadius(radius - 10)
                                .innerRadius(0);

                        var pie = d3.layout.pie()
                                .sort(null)
                                .value(function(d) { return d.SmArea; });

                        var svg = d3.select("#piechart").append("svg")
                                .attr("width", width)
                                .attr("height", height)
                                .append("g")
                                .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

                        //D3 饼图绘制
                        var g = svg.selectAll(".arc")
                                .data(pie(data))
                                .enter().append("g")
                                .attr("class", "arc");
                        g.append("path")
                                .attr("d", arc)
                                .style("fill", function(d) { return color(d.data.NAME); });
                        g.append("text")
                                .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
                                .attr("dy", "0.35em")
                                .style("text-anchor", "middle")
                                .text(function(d) { return d.data.NAME; });
                    }
                    else{
                        //清除饼图
                        document.getElementById("piechart").innerHTML = "";
                    }
                }
            }
        };

        //添加图层
        function addLayer() {
            var center = new SuperMap.LonLat(11733502.481499, 4614406.969325);
            map.addLayers([layer, d3Layer, utfgrid]);
            map.setCenter(center, 4);
        }
    </script>
</head>
<body onload="init()">
<div id="map"></div>
</body>
</html>